package com.haohe.wx.util;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;



/**
 * 
 * @Title EmailSend.java
 * @Description TODO
 * @author liming.zhao@haohedata.com
 * @date 2015-6-29 
 * @time 上午11:15:45
 */
public enum EmailSend {

	INSTANCE {

		@Override
		public void init(String tempHost, String tempUsername, String tempPassword) {
			host = tempHost;
			username = tempUsername;
			password = tempPassword;
		}

		@Override
		public void send(String receiver, String subject, String content) {
			try {
				Properties props = new Properties();
				// Setup mail server
				props.put("mail.smtp.host", host);// 设置smtp主机
				props.put("mail.smtp.auth", "true");// 使用smtp身份验证
				Session session = Session.getDefaultInstance(props, null);
				// Define message
				MimeMessage message = new MimeMessage(session);
				message.setFrom(new InternetAddress(username, "弘康人寿", "UTF-8"));
				message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver)); // 收信人
				message.setSubject(subject, "UTF-8");
				// 加入正文
				Multipart multipart = new MimeMultipart();// 复杂邮件主结构
				MimeBodyPart messageBodyPart = new MimeBodyPart();
				messageBodyPart.setContent(content, "text/html;charset=UTF-8");
				multipart.addBodyPart(messageBodyPart);

				message.setContent(multipart);
				message.saveChanges();
				// 发送邮件
				Transport transport = session.getTransport("smtp");
				transport.connect(host, username, password);
				transport.sendMessage(message, message.getAllRecipients());
//				EmailLog.INFO("邮件发送成功，接受者：" + receiver + "，内容：" + content);
			} catch (Exception e) {
//				EmailLog.ERROR("邮件发送出错", e);
			}
		}
	};

	protected String host = null;

	protected String username = null;

	protected String password = null;

	/**
	 * 初始化
	 * 
	 * @param host
	 * @param username
	 * @param password
	 */
	public abstract void init(String host, String username, String password);

	/**
	 * 发送
	 * 
	 * @param emailHub
	 * @return
	 * @throws AddressException
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	public abstract void send(String receiver, String subject, String content);

}